package payment.api;

import java.io.IOException;
import java.io.InputStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class Pay implements HttpHandler {
    /**
     * 检测UA中关于微信和支付宝的标识，其他弹出提示
     */
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String token = exchange.getRequestURI().toString().replace("/pay?token=", "");
        var ua = exchange.getRequestHeaders().get("User-agent");
        var method = PayMethod.OTHER;
        for (var s : ua) {
            if (s.contains("WeChat") || s.contains("Wechat")) {
                method = PayMethod.WX;
                break;
            }
            if (s.contains("Alipay")) {
                method = PayMethod.ZFB;
                break;
            }
        }
        String html = "";
        if (method.equals(PayMethod.OTHER)) {
            InputStream is = Pay.class.getResourceAsStream("other.html");
            html = new String(is.readAllBytes());
        } else {
            InputStream is = Pay.class.getResourceAsStream("pay.html");
            html = String.format(new String(is.readAllBytes()), token, method.toString(), token);
        }

        exchange.sendResponseHeaders(200, 0);
        exchange.getResponseBody().write(html.getBytes());
        exchange.close();
    }

    public static enum PayMethod {
        WX,
        ZFB,
        OTHER
    }
}
